package com.liuchuanzheng.lcz_study_demo.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase

/**
 * @author 刘传政
 * @date 2021/8/18 10:37
 * QQ:1052374416
 * 电话:18501231486
 * 作用:
 * 注意事项:
 */
@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        private var instance: AppDatabase? = null
        fun getInstance(context: Context): AppDatabase {
            if (instance == null) {
                instance = Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "user.db")
                        //数据库升级的配置
                    .addMigrations(object :Migration(1,2){
                        /**
                         * Should run the necessary migrations.
                         *
                         *
                         * This class cannot access any generated Dao in this method.
                         *
                         *
                         * This method is already called inside a transaction and that transaction might actually be a
                         * composite transaction of all necessary `Migration`s.
                         *
                         * @param database The database instance
                         */
                        override fun migrate(database: SupportSQLiteDatabase) {
                            //新曾电话号码字段
                            database.execSQL("alter table tb_user_info add phone INTEGER")
                        }

                    })
                    //最好只在测试时使用.真正的数据操作要放在子线程
                    .allowMainThreadQueries()
                    .build()
            }
            return instance as AppDatabase
        }
    }
}